import 'package:flutter/material.dart';
import 'package:get/get.dart';

extension GetExtension on GetInterface {
  /// 获取int路由参数
  int? getParamInt(String key, [int? defaultValue]) {
    final value = Get.parameters[key];

    if (value == null) {
      return defaultValue;
    } else {
      return int.tryParse(value);
    }
  }


  /// 获取bool路由参数
  ///
  /// 可通过[condition]自定义对比函数
  bool getParamBool(String key, [bool Function(String? value)? condition]) {
    bool _isTrue(String? value) =>
        value == 'true' || value == '1' || value == 'yes';

    final value = Get.parameters[key];
    return (condition ?? _isTrue).call(value);
  }


  /// 获取某个参数
  String? getParam(String key, [String? defaultValue]) {
    return Get.parameters[key] ?? defaultValue;
  }


  /// 判断路由是否相同
  ///
  /// [route] 用于对比的路由, null 则取 Get.currentRoute
  bool isCurrentRoute(String routePath, [String? route]) {
    final uri = Uri.tryParse(route ?? currentRoute);

    return uri != null && uri.path.toLowerCase() == routePath.toLowerCase();
  }
}

extension CustomStateExt<T> on StateMixin<T> {
  /// 带动画的obx
  Widget obxAnimated(
    NotifierBuilder<T?> widget, {
    Widget Function(String? error)? onError,
    Widget? onLoading,
    Widget? onEmpty,
  }) {
    return SimpleBuilder(builder: (_) {
      Widget child;
      if (status.isLoading) {
        child = onLoading ?? const Center(child: CircularProgressIndicator());
      } else if (status.isError) {
        child = onError != null
            ? onError(status.errorMessage)
            : Center(child: Text('A error occurred: ${status.errorMessage}'));
      } else if (status.isEmpty) {
        child = onEmpty ??
            const SizedBox.shrink(); // Also can be widget(null); but is risky
      } else {
        child = widget(state);
      }

      return AnimatedSwitcher(
          duration: const Duration(milliseconds: 200),
          child: child,
          transitionBuilder: (Widget child, Animation<double> animation) {
            // 透明渐变
            return FadeTransition(opacity: animation, child: child);
          });
    });
  }
}
